define(["Zepto", 
        "underscore", 
        "Backbone"
], function($, _, Backbone) {

  var SessionModel = Backbone.Model.extend({
  
    urlRoot: '/session',
    initialize: function () {
      // Per ora cancella la sessione locale ad ogni avvio dell'app.
      // In seguito, commentare la riga seguente per mantenere la sessione
      // anche quando l'utente chiude l'app.
      // window.localStorage.clear();
    },

    login: function(creds) {
      var that = this;
      $.ajax({
        url: 'https://api.parse.com/1/login',
        dataType: 'json',
        contentType: 'application/json',
        data: creds,
        headers : {
          "X-Parse-Application-Id" : "0dIPUo9QsGjbp2G0H8qXB7tn8kqSSR6GiGkFm75x",
          "X-Parse-REST-API-Key" : "MIOI1uSRp8INLA9C7BFKSBRdimGN3fJvkY8me62r"
        },
        success: function(data, status, xhr) { 
          // alert(xhr.status);
          // alert(xhr.responseText);
          // alert(data.sessionToken);
          window.localStorage.setItem("currentUser", JSON.stringify(data));
          // Set auth to true to trigger a change:auth event
          that.set({auth: true});
        },    
        error: function(xhr, errorType, error) {
          //alert('Errore: ' + xhr + '::::' + error + '::::' + errorType);
          //alert('Error' + xhr.status);
          alert(xhr.responseText);
        }
      });
    },

    logout: function() { 
      window.localStorage.clear();
      // Set auth to false to trigger a change:auth event
      this.set({auth: false});
    },

    getAuth: function(callback) {
      if(window.localStorage.getItem("currentUser")) {
        // alert('getAuth() = '+window.localStorage.getItem("currentUser"));
        var currentUser = JSON.parse(window.localStorage.getItem("currentUser"));
        return currentUser;
      }
      return null;
    }

    // ,setAuth: function(user) {
    //   window.localStorage.setItem("currentUser", JSON.stringify(user));
    //   alert(JSON.stringify(user));

    //   this.set({auth: true});
    // }
  });
  return new SessionModel();

});